<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>localStorage</title>
</head>

<body>
  <h2>localStorage</h2>

  <button onclick="saveData()">点我保存数据</button>
  <hr />
  <button onclick="readData()">点我读取数据</button>
  <hr />
  <button onclick="removeData()">点我删除数据</button>
  <hr />
  <button onclick="clearData()">点我清空数据</button>


  <script>
    let p = {
      name: 'jian',
      age: 18
    }

    function saveData() {
      localStorage.setItem('msg', 'hello,jian!')
      // 将数字型转换为字符型
      localStorage.setItem('age', 18)
      // 将对象转换为字符串
      localStorage.setItem('person', JSON.stringify(p))
    }
    function readData() {
      console.log(localStorage.getItem('msg'))

      console.log(localStorage.getItem('age'))

      const per = localStorage.getItem('person')
      //将字符串转换为对象
      console.log(JSON.parse(per));

      console.log(localStorage.getItem('age2'));  //null

    }

    function removeData() {
      localStorage.removeItem('msg')
      localStorage.removeItem('person', JSON.stringify(p))
    }

    function clearData() {
      localStorage.clear()

    }
  </script>
</body>

</html>